<template>
  <el-container>
    <el-main ref="mainBody" class="nopadding" :style="'height:'+mainHeight+'px;'">
      <el-container>
        <el-aside class="nopadding" style="width: 145px;">
          <el-container>
            <el-header style="border: 0;margin-top: -14px;margin-bottom: -8px;">
              <el-input v-model="filterColumnName" clearable placeholder="筛选名称"></el-input>
            </el-header>
            <el-main>
              <el-collapse v-model="collapseActiveName" accordion>
                <template v-for="columnGroup in columnGroups">
                  <el-collapse-item :name="columnGroup.levelCode">
                    <template #title>
                      <ex-label code="FamsColumn" :value="columnGroup.levelCode"/>
                    </template>
                    <template #default>
                      <div class="dragList"
                           style="border: 1px solid white;padding: 2px 2px 2px 2px;">
                        <draggable v-model="columnGroup.list" animation="300" item-key="id"
                                   :group="{name:'cardStyle'}" :sort="false"
                                   @change="dragChange">
                          <template #item="{ element }">
                            <div class="item" v-if="element.visible">{{
                                element.name
                              }}
                            </div>
                          </template>
                        </draggable>
                      </div>
                    </template>
                  </el-collapse-item>
                </template>
              </el-collapse>
            </el-main>
          </el-container>
        </el-aside>
        <el-main class="nopadding">
          <el-container>
            <el-main class="nopadding" style="overflow: hidden;position: relative;">
              <el-form v-if="isAlready" :model="mainForm" :rules="mainRules"
                      label-position="right" ref="dataForm">
              <el-tabs v-model="activeName" style="height: 100%;" tab-position="left"
                       @tab-remove="removeTab" @tab-click="clickTab" :before-leave="beforeLeave">
                <el-tab-pane v-for="tab in cardForm.tabs" :label="tab.label" :name="tab.name"
                             :closable="tab.closable">
                  <el-container :style="'height:'+ paneHeight+'px;'">
                    <el-header class="nopadding">
                      <el-row style="width: 100%;">
                        <el-col :span="6">
                          <el-form-item label="分组名称">
                            <el-input v-model="tab.label"></el-input>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="每行数量">
							  <ex-select v-model="tab.colNum" dict-code="FORM_ITEM_SPAN" placeholder="请选择"></ex-select>
<!--                            <el-select v-model="tab.colNum" placeholder="请选择" filterable-->
<!--                                       clearable>-->
<!--                              <el-option-->
<!--                                  v-for="item in this.$cache.dic.options('FORM_ITEM_SPAN')"-->
<!--                                  :key="item.value" :label="item.label"-->
<!--                                  :value="parseInt(item.value)"/>-->
<!--                            </el-select>-->
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="标签统一宽度">
                            <el-input-number v-model="tab.labelWidth"></el-input-number>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-header>
                    <el-main class="nopadding" style="margin-top: -15px;">
                      <el-empty v-if="tab.cardStyles.length===0"
                                style="position: absolute;z-index: 0;width: 98%;height: 95%;border: 1px dashed #e6e6e6;margin: 10px 2px 2px 0;"
                                description="快来布局吧~~~"/>

                        <div class="mainDragList">
                          <draggable v-model="tab.cardStyles" animation="300"
                                     :style="'height:'+ mainDragHeight+'px;background-color: #FFFFFF0D'"
                                     item-key="id" :group="{name:'cardStyle'}"
                                     @change="mainDragChange(tab.cardStyles,tab.name)">
                            <template #item="{ element }">
                              <el-col class="mainTtem"
                                      :span="element.colSpan?element.colSpan:tab.colNum"
                                      @click="selectChange(element)">
                                <ex-form-item :column="element" :model="mainForm"
                                              :size="element.widgetSize?element.widgetSize:tab.widgetSize" :label-width="tab.labelWidth+'px'"/>
                              </el-col>
                            </template>
                          </draggable>
                        </div>

                    </el-main>
                  </el-container>
                </el-tab-pane>
                <el-tab-pane name="addTab">
                  <template #label>
                    <el-tag style="width:100%;">添加分组</el-tag>
                  </template>
                </el-tab-pane>
              </el-tabs>
              </el-form>
              <div class="innerDrawer">
                <el-drawer v-model="drawerModel" size="130px;" direction="btt" :withHeader="false"
                           style="position: absolute;z-index: -1;">
                  <el-form label-width="100" label-position="right" style="padding: 10px 10px 0 10px;">
                    <el-row>
                      <el-col :span="6" class="colClass">
                        <el-form-item label="属性名称">
                          {{ currentItem.name }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="6" class="colClass">
                        <el-form-item label="是否只读">
							<ex-radio-group v-model="currentItem.isReadonly" dict-code="IS_READONLY" size="small"  @change="readonlyChange(currentItem)"></ex-radio-group>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6" class="colClass">
                        <el-form-item label="是否必填">
							<ex-radio-group v-model="currentItem.isRequired" dict-code="IS_REQUIRED" size="small" @change="requiredChange(currentItem)" :disabled="currentItem.isReadonly==='1'"></ex-radio-group>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6" class="colClass">
                        <el-form-item label="占用列">
                          <el-input-number size="small" v-model="currentItem.colSpan" :min="0"
                                           :max="24"></el-input-number>
                        </el-form-item>
                      </el-col>

                      <el-col v-if="currentItem.widgetType!=='file'" :span="6" class="colClass">
                        <el-form-item label="控件尺寸">
							<ex-select  v-model="currentItem.widgetSize" dict-code="WIDGET_SIZE" size="small" placeholder="请选择"></ex-select>
                        </el-form-item>
                      </el-col>
                      <el-col v-if="currentItem.widgetType!=='file'" :span="6" class="colClass">
                        <el-form-item label="宽度">
                          <el-input-number size="small" v-model="currentItem.width" :min="100"
                                           :max="1000"></el-input-number>
                        </el-form-item>
                      </el-col>
                      <template
                          v-if="currentItem.widgetType==='text'||currentItem.widgetType==='textarea'">
                        <el-col :span="6" class="colClass">
                          <el-form-item label="最小长度">
                            <el-input-number size="small" v-model="currentItem.minLength"
                                             :min="0"
                                             :max="300"
                                             @change="lengthChange(currentItem)"></el-input-number>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6" class="colClass">
                          <el-form-item label="最大长度">
                            <el-input-number size="small" v-model="currentItem.maxLength"
                                             :min="currentItem.minLength" :max="300"
                                             @change="lengthChange(currentItem)"></el-input-number>
                          </el-form-item>
                        </el-col>
                      </template>
                      <template v-if="currentItem.widgetType==='number'">
                        <el-col :span="6" class="colClass">
                          <el-form-item label="最小值">
                            <el-input-number size="small" v-model="currentItem.minValue"
                                             :min="0"
                                             :max="9999999999"></el-input-number>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6" class="colClass">
                          <el-form-item label="最大值">
                            <el-input-number size="small" v-model="currentItem.maxValue"
                                             :min="currentItem.minValue"
                                             :max="9999999999"></el-input-number>
                          </el-form-item>
                        </el-col>
                      </template>

                      <template v-if="currentItem.widgetType==='text'||currentItem.widgetType==='textarea'||currentItem.widgetType==='date'||currentItem.widgetType==='datetime'||currentItem.widgetType==='number'">
                        <el-col :span="6" class="colClass">
                          <el-form-item label="输入提示">
                            <el-input size="small" v-model="currentItem.placeHolder" placeholder="请输入提示信息" clearable></el-input>
                          </el-form-item>
                        </el-col>
                      </template>

                      <template v-if="currentItem.widgetType==='textarea'">
                        <el-col :span="6" class="colClass">
                          <el-form-item label="行数">
                            <el-input-number size="small" v-model="currentItem.height"
                                             :min="1"
                                             :max="50"></el-input-number>
                          </el-form-item>
                        </el-col>
                      </template>
                      <template v-if="currentItem.widgetType==='file'">
                        <el-col :span="6" class="colClass">
                          <el-form-item label="最大数量">
                            <el-input-number size="small" v-model="currentItem.height"
                                             :min="1"
                                             :max="10"></el-input-number>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6" class="colClass">
                          <el-form-item label="单文件大小">
                            <el-input-number size="small" v-model="currentItem.maxLength"
                                             :min="1" :max="10"></el-input-number>MB
                          </el-form-item>
                        </el-col>
                      </template>
                      <el-col :span="6" class="colClass">
                        <el-form-item label="前置属性">
							<ex-select v-model="currentItem.preAttributeCode" dict-code="FamsColumn" placeholder="请选择" size="small"></ex-select>
                        </el-form-item>
                      </el-col>
                      <el-col v-if="currentItem.widgetType!=='file'" :span="6" class="colClass">
                        <el-form-item label="默认值">
                          <ex-form-item size="small" :column="currentItem" :model="mainForm"
                                        :show-label="false"/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </el-drawer>
              </div>
            </el-main>
          </el-container>
        </el-main>
      </el-container>
    </el-main>
  </el-container>

  <el-dialog v-model="add_tab_dialog" width="500">
    <template #default>
      <div style="width: 90%;">
        <el-form-item label="分组名称" label-width="100">
          <el-input v-model="newTabName"/>
        </el-form-item>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto;text-align: center;">
        <el-button plain type="primary" @click="addTab">确 认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import draggable from 'vuedraggable'
import ExFormItem from "@/components/exFormItem/index.vue";
import ExLabel from "@/components/exLabel/index.vue";
import Select from "@/components/scWorkflow/select.vue";
import ExSelect from "@/components/exSelect/index.vue";
import ExRadioGroup from "@/components/exRadioGroup/index.vue";

export default {
  name: 'cardDesign',
  components: {
	  ExRadioGroup,
	  ExSelect,
    Select,
    ExLabel,
    ExFormItem,
    draggable
  },
  props: {
    cardForm: {},
  },
  data() {
    return {
      add_tab_dialog: false,
      drawerModel: false,
      mainHeight: 100,
      paneHeight: 300,
      mainDragHeight: 300,
      filterColumnName: '',
      newTabName: '',
      activeName: '',
      collapseActiveName: '',
      mainForm: {},
      mainRules: {},
      columns: [],
      columnGroups: [],
      currentItem: null,
      windowBody: window,
      isAlready:false,
    }
  },
  created() {
    this.resetMainHeight();
  },
  mounted() {
    this.initColumns();
    if (this.cardForm) {
      if (this.cardForm.tabs&&this.cardForm.tabs.length>0) {
        this.activeName = this.cardForm.tabs[0].name;
      } else {
        this.cardForm.tabs = [this.newTab('基本信息', 'tab1', true)];
        this.cardForm.widgetSize = 'default';
        this.activeName = this.cardForm.tabs[0].name;
      }
    }
    window.addEventListener("resize", this.resetMainHeight);
  },
  beforeUnmount() {
    window.removeEventListener("resize", this.resetMainHeight);
  },
  watch: {
    filterColumnName(val) {
      this.columns.forEach(column => column.visible = column.name.includes(val));
    },
  },
  methods: {
    resetMainHeight() {
      let mainHeight = window.innerHeight - 240;
      if (mainHeight <= 300) {
        mainHeight = 300;
      }
      this.mainHeight = mainHeight;
      this.paneHeight = mainHeight;
      this.mainDragHeight = this.paneHeight - 50;
    },
    newTab(label, name, closable) {
      return {label: label, name: name, cardStyles: [], closable: closable, colNum: 8, labelWidth: 100, orderWeight: 0};
    },
    initColumns: async function () {
      //已布局的字段处理，先放到一个集合中，后面从所有字段中过滤，同时组装字段基本信息
      let hasDragColumns = [];
      if (this.cardForm.id) {
        if (Array.isArray(this.cardForm.tabs)) {
          this.cardForm.tabs.forEach(tab => {
            tab.closable = true;
            if (Array.isArray(tab.cardStyles)) {
              tab.cardStyles.forEach(cardStyle => {
                cardStyle.tabName = tab.name;
                hasDragColumns.push(cardStyle);
              });
            }
          });
        }
      }
      //查询所有字段信息
      let rsp = await this.$API.asset.column.all.post({isGroup: '0'});
      this.columns = rsp.data;
      this.columns.forEach((column,position) => {
        //字段样式的默认属性
        let columnStyle = {
          cardId: '',
          columnId: column.id,
          tabName: '',
          isReadonly: '0',
          isRequired: '0',
          colSpan: 0,
          minValue: 0,
          minLength: 0,
          groupPosition: position,
          defaultValue: null,
          visible: true,
        };
        Object.assign(column, columnStyle);

        //组装已布局字段的基本信息
        hasDragColumns.forEach(dragColumn => {
          if (dragColumn.columnId === column.columnId) {
            Object.assign(column, dragColumn);//先把已布局字段的属性合并到字段基本信息
            Object.assign(dragColumn, column);//再把字段信息重新合并到已布局字段，完成信息组装
            this.mainForm[dragColumn.code] = dragColumn.defaultValue;//默认值
            this.setRules(dragColumn);
          }
        });

        let columnGroup = this.columnGroups.filter(group => group.levelCode === column.parentLevelCode)[0];
        if (columnGroup) {
          //对没有布局的字段进行分组处理
          if (column.tabName === '') {
            columnGroup.list.push(column)
          }
        } else {
          columnGroup = {levelCode: column.parentLevelCode, list: []};
          //对没有布局的字段进行分组处理
          if (column.tabName === '') {
            columnGroup.list.push(column)
          }
          this.columnGroups.push(columnGroup);
        }
      });
      this.collapseActiveName = this.columnGroups[0].levelCode;
      this.isAlready = true;
    },
    //当切换到添加分组tab时，禁止切换
    beforeLeave: function (activeName, oldActiveName) {
      if ('addTab' === activeName) {
        return false;
      }
    },
    openAddTab() {
      this.add_tab_dialog = true;
    },
    //添加卡片分组tab
    addTab: function () {
      if (!this.newTabName || this.newTabName.trim().length === 0) {
        this.$message.warning({message: '请输入分组名称'});
        return;
      }
      if (this.cardForm.tabs.filter(tab => tab.label === this.newTabName).length > 0) {
        this.$message.warning({message: '分组名称已存在'});
        return;
      }
      this.add_tab_dialog = false;
      let orderWeight = this.cardForm.tabs.length + 1;
      let tab = this.newTab(this.newTabName, "tab" + orderWeight, true);
      tab.orderWeight = orderWeight;
      this.cardForm.tabs.push(tab);
      this.activeName = tab.name;
    },
    //点击添加分组tab时，打开添加界面
    clickTab: function (pane) {
      if ('addTab' === pane.paneName) {
        this.openAddTab();
      }
    },
    //删除分组时，重置该分组已布局的字段
    removeTab: function (tabName) {
      this.$confirm(`该分组已布局字段将全部清除`, '提示', {
        type: 'warning'
      }).then(() => {
        this.cardForm.tabs.forEach((tab, index) => {
          if (tab.name === tabName) {
            let nextTab = this.cardForm.tabs[index + 1] || this.cardForm.tabs[index - 1];
            if (nextTab) {
              this.activeName = nextTab.name
            }
            tab.cardStyles.forEach(item => {
              this.reStoreColumn(item);
            });
          }
        });
        this.cardForm.tabs = this.cardForm.tabs.filter((tab) => tab.name !== tabName);
      }).catch(() => {
      });
    },
    //拖入字段栏时，重置字段的分组及位置
    dragChange: function (event) {
      if (event.added) {
        this.reStoreColumn(event.added.element);
      }
    },
    //还原字段的分组及位置
    reStoreColumn: function (element) {
      this.columnGroups.forEach(columnGroup => {
        columnGroup.list = columnGroup.list.filter(column => column.columnId !== element.columnId);
        if (columnGroup.levelCode === element.parentLevelCode) {
          columnGroup.list.push(element);
          columnGroup.list.sort((a, b) => a.groupPosition - b.groupPosition);
        }
      });
    },
    //布局拖动变化时，更新该分组下所有字段的所属分组及排序
    mainDragChange: function (list, tabName) {
      list.forEach((column, index) => {
        column.tabName = tabName;
        column.orderWeight = index;
      });
    },
    //点击其中一个字段时，将当前选中字段替换成点击的字段
    selectChange: function (column) {
      this.currentItem = column;
      this.drawerModel = true;
    },
    /**
     * 设置字段的验证规则
     * @param currentItem
     */
    setRules(currentItem) {
      this.lengthChange(currentItem);
      this.requiredChange(currentItem);
      this.readonlyChange(currentItem);
    },
    //当字段长度设置变化时，设置预览验证规则
    lengthChange: function (currentItem) {
      if(currentItem.widgetType==='file'){
        return;
      }
      let rules = this.mainRules[currentItem.code];
      if (!rules) {
        rules = [];
      }
      rules = rules.filter(rule => rule.id !== 'length');
      let rule;
      if (currentItem.minLength && currentItem.maxLength) {
        rule = {
          id: 'length',
          min: currentItem.minLength,
          max: currentItem.maxLength,
          message: currentItem.name + '的长度必须在 ' + currentItem.minLength + ' 到 ' + currentItem.maxLength + ' 个字符',
          trigger: 'blur'
        };
      } else if (currentItem.minLength) {
        rule = {
          id: 'length',
          min: currentItem.minLength,
          message: currentItem.name + '不能小于' + currentItem.minLength + '个字符',
          trigger: 'blur'
        };
      } else {
        rule = {
          id: 'length',
          max: currentItem.maxLength,
          message: currentItem.name + '不能大于' + currentItem.maxLength + '个字符',
          trigger: 'blur'
        };
      }
      rules.push(rule);
      this.mainRules[currentItem.code] = rules;
    },
    //当字段只读属性发生变化时，设置是否可编辑，并且重置对应是否必须的预览验证规则
    readonlyChange: function (currentItem) {
      if (currentItem.isReadonly === '1') {
        this.mainRules[currentItem.code] = [];
        if(this.isAlready){
          this.$refs.dataForm.clearValidate();
        }
      }else{
        this.lengthChange(currentItem);
        this.requiredChange(currentItem);
      }
    },
    //字段必填属性发生变化时，设置预览验证规则
    requiredChange: function (currentItem) {
      let rules = this.mainRules[currentItem.code];
      if (!rules) {
        rules = [];
      }
      if (currentItem.isRequired === '0') {
        rules = rules.filter(rule => rule.id !== 'required');
      } else {
        let rule = {
          id: 'required',
          required: true,
          message: currentItem.name + '不能为空',
          trigger: "blur"
        };
        rules.push(rule);
      }
      this.mainRules[currentItem.code] = rules;
    },
    //添加
    add() {
      this.$nextTick(() => {
        this.$refs.editDialog.open({});
      })
    },
  }
}
</script>

<style scoped>
.dragList {
  overflow: auto;
  height: 100%;
}

.group {
  float: left;
  color: #72b1f8;
  border: #A5D0FF;
  background: #A5D0FF4D;
  width: 100%;
  height: 25px;
  padding: 1px 0 0 2px;
  margin: 2px 0 2px 0;
}

.item {
  cursor: move;
  background: #fff;
  width: 95%;
  height: 35px;
  line-height: 35px;
  text-align: center;
  padding: 1px 1px 0 2px;
  margin: 2px 0 2px 0;
  border: 1px dashed #e6e6e6;
}

.mainDragList {
  overflow: auto;
}

.mainTtem {
  cursor: move;
  float: left;
  background: #fff;
  width: 100%;
  min-height: 50px;
  //line-height: 50px;
  text-align: center;
  horiz-align: center;
  padding: 8px 5px 0 5px;
  margin: 0 0 0 0;
  border: 1px dashed #e6e6e6;
}

.dragList .sortable-ghost {
  opacity: 0.5;
}

.colClass {
  height: 35px;
}

.innerDrawer {
  :deep .el-overlay {
    position: absolute;
  }
}
</style>
